package util;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.io.*;
import java.util.Map;

// 该类与生成、读取二维码的类大同小异，可以参见二维码的工具类或参阅文档。
public class BarcodeUtils {
    private String data;
    private String path;
    private String charset;
    private Map<EncodeHintType, ErrorCorrectionLevel> map;

    public BarcodeUtils(String data, String path, String charset, Map<EncodeHintType, ErrorCorrectionLevel> map) {
        this.data = data;
        this.path = path;
        this.charset = charset;
        this.map = map;
    }

    public void makeBarcode(int height, int width) throws IOException, WriterException {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(new String(data.getBytes(charset), charset),
                                                             BarcodeFormat.CODE_128,
                                                             width, height);
        MatrixToImageWriter.writeToFile(bitMatrix, path.substring(path.lastIndexOf('.')+1), new File(path));
    }

    public static String readBarcode(String path) throws IOException, NotFoundException {
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
                new BufferedImageLuminanceSource(
                        ImageIO.read(new FileInputStream(path))
                )
        ));
        Result result = new MultiFormatReader().decode(binaryBitmap);
        return result.getText();
    }
}
